package com.rlax.framework.util;

import java.math.BigDecimal;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

public class CommonUtils {

	public static String getRandNum(int charCount) {
		String charValue = "";
		for (int i = 0; i < charCount; i++) {
			char c = (char) (randomInt(0, 10) + '0');
			charValue += String.valueOf(c);
		}
		return charValue;
	}
	
	public static int randomInt(int from, int to) {
		Random r = new Random();
		return from + r.nextInt(to - from);
	}
	
	/**
	 * 保留几位小数
	 * @param n 浮点数
	 * @param k 保留位数
	 * @return
	 */
	public static Double keepDecimal(Double n, int k) {
		BigDecimal bd = new BigDecimal(n);
		return bd.setScale(k, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	/**
	 * 获取IP
	 * @param request
	 * @return
	 */
	public static String getRequsetIp(HttpServletRequest request) {
	    String ip = request.getHeader("x-forwarded-for");    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	        ip = request.getHeader("Proxy-Client-IP");    
	    }    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	        ip = request.getHeader("WL-Proxy-Client-IP");    
	    }    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	        ip = request.getRemoteAddr();    
	    }    
	    return ip;  
	}
}
